<script setup>
import { ref, computed } from 'vue'
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import ToSearch from '@/components/ToSearch.vue'
import DishItem from '@/components/DishItem.vue'
import MerchantItem from '@/components/MerchantItem.vue'
import { searchDishAPI, searchMerchantAPI, searchIngredientAPI } from '@/api/search'

// 页面参数
const searchType = ref('dish') // dish, merchant, ingredient
const searchKeyword = ref('')

// 搜索状态
const searchResults = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const total = ref(0)

// 搜索模式配置
const searchModes = {
  dish: { label: '菜品', icon: 'caipin', component: 'DishItem' },
  merchant: { label: '店铺', icon: 'shangpu', component: 'MerchantItem' },
  ingredient: { label: '食材', icon: 'shicai', component: 'DishItem' }
}

// 当前搜索模式
const currentMode = computed(
  () => searchModes[searchType.value] || searchModes.dish
)

// 筛选器状态
const activeSort = ref('综合排序')
const activeCalorie = ref('')

// 加载搜索结果
const loadSearchResults = async (isFirstLoad = false) => {
  if (loading.value || finished.value) return
  // 如果没有搜索关键词，不发起请求
  if (!searchKeyword.value.trim()) return

  loading.value = true
  try {
    // 如果是首次加载，重置页码
    const page = isFirstLoad ? 1 : currentPage.value
    let response
    // 根据类型调用不同接口
    if (searchType.value === 'dish') {
      response = await searchDishAPI(searchKeyword.value, page, 10)
    } else if (searchType.value === 'merchant') {
      response = await searchMerchantAPI(searchKeyword.value, page, 10)
    } else if (searchType.value === 'ingredient') {
      response = await searchIngredientAPI(searchKeyword.value, page, 10)
    } else {
      response = { code: 404, data: [] }
    }

    if (isFirstLoad) {
      searchResults.value = []
      currentPage.value = 1
      finished.value = false
    }

    // 处理API响应数据（兼容后端返回格式 code/data/total）
    if (
      response.code === 1 &&
      response.data &&
      Array.isArray((response.data.records || response.data)) &&
      ((response.data.records && response.data.records.length > 0) || (Array.isArray(response.data) && response.data.length > 0))
    ) {
      // 兼容 records/list/array
      let newResults = response.data.records || response.data.list || response.data || []
      if (Array.isArray(newResults)) {
        newResults = newResults.map((item, index) => {
          if (searchType.value === 'merchant') {
            return {
              id: item.id || Date.now() + Math.random() + index,
              name: item.merchant || '',
              location: item.location || '',
              dishName: item.dishName || '',
              calorie: item.calorie || 0,
              ...item
            }
          } else {
            return {
              ...item,
              id: item.id || Date.now() + Math.random() + index
            }
          }
        })
      }
      if (isFirstLoad) {
        searchResults.value = newResults
        total.value = response.data.total || newResults.length
      } else {
        searchResults.value.push(...newResults)
      }
      currentPage.value = page + 1
      if (
        newResults.length < 10 ||
        searchResults.value.length >= (response.data.total || 0)
      ) {
        finished.value = true
      }
    } else {
      // 没有更多数据
      if (isFirstLoad) {
        searchResults.value = []
        total.value = 0
      }
      finished.value = true
    }
  } catch (error) {
    console.error('搜索失败:', error)
    uni.showToast({
      title: '搜索失败，请稍后重试',
      icon: 'none'
    })
    if (isFirstLoad) {
      searchResults.value = []
      total.value = 0
    }
    finished.value = true
  } finally {
    loading.value = false
  }
}

// 页面加载
onLoad((options) => {
  if (options.type) {
    searchType.value = options.type
  }
  if (options.keyword) {
    searchKeyword.value = decodeURIComponent(options.keyword)
    loadSearchResults(true)
  }
})

// 触底加载更多
onReachBottom(() => {
  loadSearchResults(false)
})

// 下拉刷新
onPullDownRefresh(() => {
  searchResults.value = []
  finished.value = false
  loadSearchResults(true).then(() => {
    uni.stopPullDownRefresh()
  })
})
</script>

<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="header-content">
        <view class="title-section">
          <view class="title">
            <text :class="'iconfont icon-' + currentMode.icon"></text>
            <text>{{ currentMode.label }}搜索</text>
          </view>
          <view class="search-info" v-if="searchKeyword">
            <view class="keyword-badge">
              <text>"{{ searchKeyword }}"</text>
            </view>
            <view v-if="!loading || searchResults.length > 0" class="result-count">
              <text>找到 {{ searchResults.length }} 个结果</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <ToSearch />

    <!-- 分割线 -->
    <view class="divider"></view>

    <!-- 搜索结果区域 -->
    <view class="search-results-section" v-if="searchKeyword">
      <!-- 结果列表 -->
      <view class="results-list">
        <view
          v-for="item in searchResults"
          :key="item.id"
          class="result-item-wrapper"
        >
          <DishItem v-if="currentMode.component === 'DishItem'" :dish="item" />
          <MerchantItem v-else-if="currentMode.component === 'MerchantItem'" :merchant="item" />
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <view class="loading-spinner"></view>
          <text>正在搜索{{ currentMode.label }}...</text>
        </view>

        <!-- 加载完成提示 -->
        <view
          v-if="finished && !loading && searchResults.length > 0"
          class="finished-container"
        >
          <text>🎉 所有结果已加载完成</text>
        </view>

        <!-- 无结果提示 -->
        <view
          v-if="!loading && searchResults.length === 0 && searchKeyword"
          class="no-results-container"
        >
          <view class="no-results-icon">
            <text class="iconfont icon-kongbai"></text>
          </view>
          <view class="no-results-title">
            <text>没有找到相关{{ currentMode.label }}</text>
          </view>
          <view class="no-results-subtitle">
            <text>尝试使用不同的关键词或搜索类型</text>
          </view>
          <view class="suggestions">
            <view class="suggestions-title">
              <text>搜索建议：</text>
            </view>
            <view class="suggestion-tags">
              <view class="suggestion-tag">
                <text>宫保鸡丁</text>
              </view>
              <view class="suggestion-tag">
                <text>川菜小炒</text>
              </view>
              <view class="suggestion-tag">
                <text>豆腐</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 下拉加载提示 -->
        <view
          v-if="!finished && !loading && searchResults.length > 0"
          class="scroll-tip-container"
        >
          <text>👇 下拉加载更多</text>
        </view>
      </view>
    </view>

    <!-- 空状态 (未搜索时) -->
    <view v-if="!searchKeyword" class="empty-state">
      <view class="empty-icon">
        <text class="iconfont icon-sousuo"></text>
      </view>
      <view class="empty-title">
        <text>开始搜索</text>
      </view>
      <view class="empty-subtitle">
        <text>输入关键词搜索{{ currentMode.label }}信息</text>
      </view>
      <view class="quick-search">
        <view class="quick-search-title">
          <text>热门搜索：</text>
        </view>
        <view class="quick-tags">
          <view class="quick-tag">
            <text>宫保鸡丁</text>
          </view>
          <view class="quick-tag">
            <text>川菜小炒</text>
          </view>
          <view class="quick-tag">
            <text>豆腐</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.search-container {
  min-height: 91vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40rpx 32rpx calc(40rpx + env(safe-area-inset-bottom)) 32rpx;
}

// 分割线
.divider {
  width: 100%;
  height: 2rpx;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(102, 126, 234, 0.3),
    transparent
  );
  margin: 24rpx 0;
}

// 搜索头部
.search-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(40rpx);
  border-radius: 40rpx;
  padding: 48rpx 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6rpx;
    background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
    background-size: 200% 100%;
    animation: gradientShift 3s ease-in-out infinite;
  }

  .header-content {
    .title-section {
      .title {
        font-size: 44rpx;
        font-weight: 700;
        color: #333;
        margin: 0 0 24rpx 0;
        display: flex;
        align-items: center;

        .iconfont {
          font-size: 48rpx;
          color: #667eea;
          margin-right: 20rpx;
        }
      }

      .search-info {
        display: flex;
        align-items: center;
        gap: 24rpx;
        flex-wrap: wrap;

        .keyword-badge {
          background: linear-gradient(45deg, #667eea, #764ba2);
          color: white;
          padding: 12rpx 32rpx;
          border-radius: 40rpx;
          font-size: 28rpx;
          font-weight: 600;
          box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
        }

        .result-count {
          font-size: 28rpx;
          color: #666;
          opacity: 0.8;
        }
      }
    }
  }
}

// 搜索结果区域
.search-results-section {
  // 结果列表
  .results-list {
    display: flex;
    flex-direction: column;
    gap: 32rpx;

    .result-item-wrapper {
      animation: fadeInUp 0.6s ease forwards;
    }

    // 加载状态
    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 80rpx 40rpx;
      color: #666;

      .loading-spinner {
        width: 64rpx;
        height: 64rpx;
        border: 6rpx solid rgba(102, 126, 234, 0.2);
        border-top: 6rpx solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 32rpx;
      }

      text {
        font-size: 28rpx;
        opacity: 0.8;
      }
    }

    // 加载完成
    .finished-container {
      text-align: center;
      padding: 80rpx 40rpx;
      color: #999;

      text {
        font-size: 28rpx;
        opacity: 0.8;
      }
    }

    // 无结果
    .no-results-container {
      text-align: center;
      padding: 120rpx 40rpx;
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(20rpx);
      border-radius: 40rpx;
      box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
      border: 2rpx solid rgba(255, 255, 255, 0.2);

      .no-results-icon {
        margin-bottom: 40rpx;

        .iconfont {
          font-size: 128rpx;
          color: #ddd;
        }
      }

      .no-results-title {
        font-size: 36rpx;
        color: #333;
        margin: 0 0 24rpx 0;
      }

      .no-results-subtitle {
        font-size: 28rpx;
        color: #666;
        margin: 0 0 48rpx 0;
        opacity: 0.8;
      }

      .suggestions {
        .suggestions-title {
          font-size: 26rpx;
          color: #999;
          margin: 0 0 24rpx 0;
        }

        .suggestion-tags {
          display: flex;
          justify-content: center;
          gap: 16rpx;
          flex-wrap: wrap;

          .suggestion-tag {
            padding: 16rpx 32rpx;
            background: rgba(102, 126, 234, 0.1);
            color: #667eea;
            border-radius: 48rpx;
            font-size: 24rpx;
            transition: all 0.3s ease;

            &:active {
              background: linear-gradient(45deg, #667eea, #764ba2);
              color: white;
              transform: translateY(-4rpx);
              box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
            }
          }
        }
      }
    }

    // 滚动提示
    .scroll-tip-container {
      text-align: center;
      padding: 60rpx 40rpx;
      color: #999;

      text {
        font-size: 26rpx;
        opacity: 0.6;
        animation: bounce 2s infinite;
      }
    }
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 160rpx 40rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20rpx);
  border-radius: 40rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);

  .empty-icon {
    margin-bottom: 48rpx;

    .iconfont {
      font-size: 144rpx;
      color: #ddd;
    }
  }

  .empty-title {
    font-size: 40rpx;
    color: #333;
    margin: 0 0 24rpx 0;
  }

  .empty-subtitle {
    font-size: 28rpx;
    color: #666;
    margin: 0 0 64rpx 0;
    opacity: 0.8;
  }

  .quick-search {
    .quick-search-title {
      font-size: 28rpx;
      color: #999;
      margin: 0 0 32rpx 0;
    }

    .quick-tags {
      display: flex;
      justify-content: center;
      gap: 24rpx;
      flex-wrap: wrap;

      .quick-tag {
        padding: 16rpx 32rpx;
        background: rgba(102, 126, 234, 0.1);
        color: #667eea;
        border-radius: 48rpx;
        font-size: 26rpx;
        transition: all 0.3s ease;

        &:active {
          background: linear-gradient(45deg, #667eea, #764ba2);
          color: white;
          transform: translateY(-4rpx);
          box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
        }
      }
    }
  }
}

// 动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(60rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20rpx);
  }
  60% {
    transform: translateY(-10rpx);
  }
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>
